import json
import serverFiles
import variableUtils
import copy
import utils
import pickle
from translations import t

_y_demo = {

    'name': 'dataSource里的描述',#这里需要翻译 #单位 

    'type': 'value',

    'triggerEvent': True,

    'boundaryGap': ['0%', '0%'],

    'offset': 0,#按位置偏移
    'show':True,

    'splitLine': {

        'show': False,#等分线

        'type': 'solid'
    },
    'axisLine':{
      'show':True,
      'lineStyle':{
          'color':'#000'
      }  
    },
    'nameTextStyle':{
        'color':'#000'
    },
    # 默认 grid 中的第一个 y 轴在 grid 的左侧（'left'），第二个 y 轴视第一个 y 轴的位置放在另一侧。
    'position':'left'
}

virtual_dict = {}



# 获取y轴索引
#yAry外部传入
#field dataSource字段
#Ext 扩展属性
#yMode 0:一个曲线对应一个轴(上下线根据相关变量)  1:单位合并，2：排序合并
#lang 多语言翻译
#return 曲线下标Index
def get_y_axis_index(yAry,field,yMode,lang,offset):
    y = copy.deepcopy(_y_demo)
    varName = field.get('varName','')
    ext_dict = field.get('ext_dict',{})
    desc = field.get('name','')
    color = field.get('color','#000000')
    LineWidth = int(field.get('LineWidth',1))
    
    Order = field.get('Order',0)#排序

    if varName == '':
        varName = ext_dict.get('variablePath','')
    
    unit = variableUtils.getUnit(varName,'')#单位
    pcs = variableUtils.getPCS(varName,1)#精度
    wmav = variableUtils.getMax(varName)
    wmiv = variableUtils.getMin(varName)
    grp = ext_dict.get('grp','')
    if grp != '':
        grp = t(lang,grp)
    # wm_offset = (wmav - wmiv) * 0.05
    # wm_offset = float(utils.format_num(wm_offset,pcs))
    y_show = ext_dict.get('y_show',1)

    if ext_dict.get('type','') in ['virtual','override']:
        unit = ext_dict.get('unit',unit)
        pcs = ext_dict.get('pcs',pcs)
        try:
            wmav = eval(ext_dict.get('wmav',str(wmav)))
            wmiv = eval(ext_dict.get('wmiv',str(wmiv)))
            wmav = float(utils.format_num(wmav,pcs))
            wmiv = float(utils.format_num(wmiv,pcs))
            # wm_offset = (wmav - wmiv) * 0.05
            # wm_offset = float(utils.format_num(wm_offset,pcs))
        except:
            wmav = 44
            wmiv = 4
            wm_offset = 40

    def join():
        
        y['position'] = 'left' if Order <= 0 else 'right'
        count = len([obj for obj in yAry if obj.get('position') == y['position']])
        y['name'] = f"{desc}\n{unit}"
        y['axisLine']['lineStyle']['color'] = color
        y['axisLine']['lineStyle']['width'] = LineWidth
        y['nameTextStyle']['color'] = color
        y['pcs'] = pcs
        y['Order'] = Order
            
        if wmav != None:
            y['max'] = wmav#+wm_offset
            y['_max'] = wmav
        else:
            y['max'] = 'auto'
            y['_max'] = 1000
            pass
        if wmiv != None:
            y['min'] = wmiv#-wm_offset
            y['_min'] = wmiv
        else:
            y['min'] = 'auto'
            y['_min'] = -1000
            pass
        
        # offset注释,没用,vue那里已处理
        # if y_show:
        #     y['offset'] = offset * count + 10
        # else:
        #     y['offset'] = -offset

        y['unit'] = unit
        y['y_show'] = y_show
        # if not y['y_show']:#这样就不会显示游标
        #     del y['min']
        #     del y['max']
        y['curve_names'] = [desc]
        yAry.append(y)
    
    if yMode == 0:#一个曲线一个轴
        join()
        return len(yAry) - 1
    elif yMode == 1:#多曲线一个相同单位的轴
        y_index = utils.find_and_modify(yAry,'unit',unit,wmav,wmiv,unit,'#000',pcs,grp)
        if y_index != -1:
            yAry[y_index]['curve_names'].append(desc)
            return y_index 
        else:
            join()
            return len(yAry) - 1
    elif yMode == 2:# 显示值和变量值 覆盖扩展值

        y_index = utils.find_and_modify(yAry,'Order',Order,wmav,wmiv,unit,'#000',pcs,grp)
        if y_index != -1:
            yAry[y_index]['curve_names'].append(desc)
            return y_index 
        else:
            join()
            return len(yAry) - 1
        pass
    return -1
#TableIndex=1 Data1 Event1 AlarmDataGroup(where1),LogDataGroup()
#
def getInitCurveOption(dataSourceName,tableId,curve_name,sub_fields,auth_groups,yMode,lang,offset):
    isRt = curve_name == 'rt'
    if sub_fields == '':
        sub_fields = []
    else:
        sub_fields = sub_fields.split(',')
    if auth_groups == '':
        auth_groups = []
    else:
        auth_groups = auth_groups.split(',')
        
    EnableField = 'RtCurveEnable' if isRt else 'HisCurveEnable'
    #找到对应的数据表
    DataN = f"Data{tableId}"
    EventN = f"Event{tableId}"#特征标签
    table = {}
    for dt in serverFiles.dataSource['DataSourceArray']:
        if dt['Name'].lower() == dataSourceName.lower():#默认 local
            for d in dt['TableArray']:
                if d['Name'].lower() == DataN.lower():
                    # print('ok')
                    table = copy.deepcopy(d)
                else:
                    # print(d['Name'])
                    pass
    if table == {}:
        raise ValueError(f"在本地DataSource.json(根据runtime.ini路径)配置文件中找不到对应的数据源 {dataSourceName} 或者在该配置下未找到{DataN}")
    

    #初始化需要返回的数据
    series = []
    color_array = []
    xAxis= {
      'type': "category",
      'data': utils.generate_time_array()
    }
    yAxis = []
    legend = {
        'data':[],
        'fields':[]
    }
    

    # 遍历TableArray下的 FieldArray
    table['FieldArray'].sort(key=lambda x: x['Order'])
    for field in table['FieldArray']:
        # 过滤EnableField为true的项virtual.hmi.motor.get.pv_speed
        varName = field.get('NameInFieldGroup')
        hasVar = variableUtils.hasVar(varName)

        try:
            Ext = field.pop('Ext','')
            ext_dict = json.loads(Ext)
            field['ext_dict'] = ext_dict
            if hasVar:
                variableUtils.syncExtDict(varName, ext_dict)
        except:
            # print(f"""Invalid JSON string.{field['Name']}""")
            ext_dict = {}
        isVirtual = ext_dict.get('type','') in ['virtual','override']

        if field.get(EnableField) and hasVar or isVirtual:
            if curve_name == 'prt' and len(sub_fields) > 0:
                # _ = varName.replace('.','_')
                if field['Name'] not in sub_fields:
                    continue
                if ext_dict.get("rpt_legend_show",1) == 0:
                    continue
            exp_auth_groups = ext_dict.get('auth',[])
            # 如果需要权限验证
            if len(exp_auth_groups) > 0:
                #一个数组里的元素，是否出现过在另一个数组里
                has = utils.any_element_in_common(auth_groups,exp_auth_groups)
                if not has:
                    continue
            field.update({
                'animation':False,
                'showSymbol':False,
                'showAllSymbol':False
            })
    
            # 修改字段名称
            name = field.pop('Desc')
            name = t(lang,name)
            field['name'] = name
            field['field'] = field.pop('Name')#f1f2f3数据库键名
            field['varName'] = field.pop('NameInFieldGroup')#变量路径
            field['lineStyle'] = {'width': field.pop('LineWidth')}
            clr = field.pop('Color')
            if clr == '': clr = utils.random_color_code()
            field['color'] = clr

            # if name == '离心力g值':
            #     breakpoint()
            # 获取y轴索引
            yIdx = get_y_axis_index(yAxis,field,yMode,lang,offset)
            if yIdx == -1:#变量不存在
                continue
            field['yAxisIndex'] = yIdx

            field['type'] = 'line'


            field['data'] = []
            wmav = variableUtils.getMax(varName,1)#临时出 上下线
            wmiv = variableUtils.getMin(varName,0)
            field['data'] = utils.generate_smooth_random_curve(wmiv,wmav)

            if isVirtual:
                virtual_dict[field['field']] = field
                # field['field'] = ext_dict.get('exp','')
            
            field.update(ext_dict.get('series',{}))
            series.append(field)
    
    # 将对象写入到文件中
    with open('curve_virtual_dict.pkl', 'wb') as f:
        pickle.dump(virtual_dict, f)

    for field in series:
        legend['data'].append(field.get('name'))
        legend['fields'].append(field.get('field'))

    # 输出结果
    result = {
        'title':'',
        'animation': False,
        'series':series,
        # 'color':color_array,
        # 'grid':getGrildLeftRight(yAxis),
        'legend':legend,
        'xAxis':xAxis,
        'yAxis':yAxis,
        'other':{
            'y_offset':offset
        }
    }
    return result

def getGrildLeftRight(yAxis):
    left_y = -1
    right_y = -1
    for y in reversed(yAxis):
        if left_y == -1 and y['position'] == 'left':
            left_y = y['offset']
        elif right_y == -1 and y['position'] == 'right':
            right_y = y['offset']
        elif left_y != -1 and right_y != -1:
            break
    return {
        'left':left_y,
        'right':right_y
    }

def getVirtualDict():
    global virtual_dict
    if len(virtual_dict) == 0:
        # 从文件中读取对象
        with open('curve_virtual_dict.pkl', 'rb') as f:
            virtual_dict = pickle.load(f)
    return virtual_dict